//
//  CalenderAddTableViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/10/15.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "CalenderAddTableViewController.h"
#import <AFNetworking.h>
#import "AllHeader.h"

#import "ExamtionModel.h"

#define examURL  @"http://arts1.dlab.com.cn/app/examapply"

#define exURL  @"http://arts1.dlab.com.cn/app/exam"


@interface CalenderAddTableViewController ()

@property (nonatomic, strong) NSString *examId;

@property (nonatomic, strong) NSMutableArray *dataArr;


@end

@implementation CalenderAddTableViewController

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        self.dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.bounces = YES;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self requestDataForExamtion];

}

/**
 *  获取考试时间列表
 */
- (void)requestDataForExamtion{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"profileId":_ID};
    
    [manage POST:exURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
             NSInteger status = [dic[@"status"] integerValue];
             if (status == 1) {
                 NSArray *arr = dic[@"list"];
                 for (NSDictionary *dict in arr) {
                     ExamtionModel *model = [[ExamtionModel alloc] init];
                     [model setValuesForKeysWithDictionary:dict];
                     [self.dataArr addObject:model];
                 }
             }
             NSLog(@"获取考试时间列表的请求结果 %@",dic);
             //解析完数据之后，在主线程中刷新数据
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self.tableView reloadData];
             });
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

/**
 *  点击添加到日历网络请求
 */
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"examId":_examId};
    
    [manage POST:examURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
             NSInteger status = [dic[@"status"] integerValue];
             if (status == 1) {
                 [MBProgressHUD show:@"已添加至日历" icon:nil view:self.view];
             }
             NSLog(@"添加到日历的请求结果 %@",dic);


         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
  return @"添加至日历";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:
 (NSInteger)section{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddCalenderCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"AddCalenderCell"];
        cell.textLabel.font = [UIFont systemFontOfSize:12];
        cell.textLabel.textColor = kCustomColor(50, 50, 70, 1);
        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
    }
        ExamtionModel *exam = (ExamtionModel *)_dataArr[indexPath.row];
        cell.textLabel.text = exam.examTime;
        cell.detailTextLabel.text = exam.province;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   ExamtionModel *exam = (ExamtionModel *)_dataArr[indexPath.row];
    _examId = exam.Id;
    [self requestData];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
